import { app, protocol ,Tray,nativeImage,Menu} from 'electron'
import path from 'path'
import { exit } from 'process'
import ElectronApp from './app'
import checkUpdate from './updater'


/**在开发环境下测试更新功能 则设置为true */
Object.defineProperty(app,'isPackaged',{
	get(){
		return false
	}
})

const electronApp=new ElectronApp()

protocol.registerSchemesAsPrivileged([
	{ scheme: 'app', privileges: { secure: true, standard: true } }
])

let tray 

app.whenReady().then(() => {

	tray = new Tray(nativeImage.createFromPath(path.join(__dirname, './logo.png')).resize({ width: 16, height: 16 }))
	const contextMenu = Menu.buildFromTemplate([
		{
			label: '退出',
			click: function () {
				app.quit()
				exit(0)
			}
		}
	])
	tray.setToolTip('Electron Demo')
	//显示程序页面
	tray.on('click', () => {
		electronApp.mainWindow?.show()
	})
	tray.setContextMenu(contextMenu)

	electronApp.whenReady()

	checkUpdate((shouldUpdate)=>{
		if(!shouldUpdate){
			electronApp.createWindow()
			electronApp.registerHandle()
		}
	})
	
})

app.on('window-all-closed', async () => {
	console.log('window-all-closed')
	await electronApp.destroyed()
	app.quit()
	exit(0)
})
app.on('before-quit',async (e)=>{
	await electronApp.destroyed()
	app.quit()
	exit(0)
})
app.on('will-quit',()=>{
	console.log('will-quit')
})

process.on('uncaughtException', error=> {
	console.log("Node Error...");
});
process.on('unhandledRejection', error => {
    console.error('unhandledRejection', error);
});